//
//  HMAddPatriarchVC.m
//  优学荟管理系统
//
//  Created by 陈辉明 on 2017/12/13.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "HMAddPatriarchVC.h"
#import "HMAddPatriarchCell.h"
#import "HMAddPatriarchModel.h"

@interface HMAddPatriarchVC () <UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITextField *searchTextField;
@property (strong, nonatomic) NSMutableArray *selectIndexs;//多选选中的行
@property (nonatomic,strong) NSMutableArray *dataSource;
@property (nonatomic,assign) BOOL isTrue;
@property (nonatomic,assign) NSInteger page;



@end

@implementation HMAddPatriarchVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"添加三好家长";
    [self setUpTableView];
  

    if (self.isUpTwo) {

    }else{
       [self setUpRefresh];
    }
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTargat:self action:@selector(itemAction) image:@"icon_back_student_sign" highImage:@"icon_back_student_sign"];
}


- (void)itemAction{
    
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

-(void)setUpTableView {
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.searchTextField.delegate = self;
    self.searchTextField.returnKeyType= UIReturnKeySearch;
     [self.tableView registerNib:[UINib nibWithNibName:@"HMAddPatriarchCell" bundle:nil] forCellReuseIdentifier:@"HMAddPatriarchCellId"];
    self.tableView.estimatedRowHeight = 90;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
}

#pragma mark - tableViewDataSource,tableViewDelegate


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  self.dataSource.count;
   
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HMAddPatriarchModel *model = self.dataSource[indexPath.row];
    HMAddPatriarchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HMAddPatriarchCellId" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = model;


    
    cell.selectButton.selected = NO;
    for (NSIndexPath *index in _selectIndexs) {
        if (index == indexPath) { //改行在选择的数组里面有记录
            cell.selectButton.selected = YES; //打勾
            break;
        }
    }
    
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //获取到点击的cell
    HMAddPatriarchCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell.selectButton.selected == YES) { //如果为选中状态
        cell.selectButton.selected = NO; //切换为未选中
        [_selectIndexs removeObject:indexPath]; //数据移除
    }else { //未选中
        cell.selectButton.selected = YES; //切换为选中
        [_selectIndexs addObject:indexPath]; //添加索引数据到数组
    }
    

}




- (IBAction)clickSureButton:(id)sender {
    
    //http://192.168.0.113:8080/StarShine/ys/yxhUser.do?action=saveThreeParent&uids=250,251
    if (self.selectIndexs.count > 0) {
        [self setEnterNetWork];
    }else {
        [SVProgressHUD showErrorWithStatus:@"请选择家长"];
    }
    
}


#pragma mark --- 上拉加载和下拉刷新方法的实现
- (void)setUpRefresh{
    
    //下拉刷新
    self.tableView.mj_header  = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downRefresh)];
    //自动更改透明度
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    //进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
    //上拉加载
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upRefresh)];
    //结束头部刷新
    [self.tableView.mj_header endRefreshing];
    //结束尾部刷新
    [self.tableView.mj_footer endRefreshing];
    
    
}

/**
 *  上拉加载
 */
- (void)upRefresh{
    
    self.isTrue = NO;
    self.page++;
    [self setNetWork];
    
}
/**
 *  下拉刷新
 */

- (void)downRefresh{
    self.isTrue = YES;
    self.page = 1;
    [self setNetWork];
    
    
}




#pragma mark - 键盘搜索处理
-(void)textFieldDidEndEditing:(UITextField *)textField{
    
    [self.searchTextField resignFirstResponder];
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if (self.searchTextField.text.length!=0) {
//        self.isUpTwo = NO;
//        [self.tableView.mj_header beginRefreshing];
        [self setUpRefresh];
        [self.searchTextField resignFirstResponder];
    }else{
        [MBProgressHUD showError:@"请输入搜索内容"];
    }
    
    return YES;
    
}

#pragma mark - 网络请求

- (void)setNetWork{
    
    //http://192.168.0.113:8080/StarShine/ys/yxhUser.do?action=selParentByOid&pageNumber=1&searchName=
    
    NSString *url;
    if (self.searchTextField.text.length != 0 &&self.searchTextField.text) {
        
        url = [NSString stringWithFormat:@"yxhUser.do?action=selParentByOid&pageNumber=%ld&searchName=%@&lessonId=%@",(long)self.page,self.searchTextField.text,self.lessionId];
        url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    } else {
        
        url = [NSString stringWithFormat:@"yxhUser.do?action=selParentByOid&pageNumber=%ld&searchName=%@&lessonId=%@",(long)self.page,@"",self.lessionId];
        url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    }
    
    
    NSLog(@"%@ %@",LLBaseURL(url),[AccountTool shareAccountTool].currentAccount.authCode);
    [SVProgressHUD setDefaultStyle:(SVProgressHUDStyleCustom)];
    [SVProgressHUD  setBackgroundColor:ColorRGB(4, 4, 4)];
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    [SVProgressHUD showWithStatus:LLLoading];
    
    [NetManager Get:LLBaseURL(url) Auth:YES Params:nil Success:^(id Obj) {
        
        if ([[Obj valueForKey:@"code"]integerValue] == 1000) {
            [SVProgressHUD dismiss];
            if (self.isTrue == YES) {
                [self.dataSource removeAllObjects];
                [self.selectIndexs removeAllObjects];
            }
            
            for (NSDictionary *dict in Obj[@"t"][@"dataList"]) {
                HMAddPatriarchModel *model = [HMAddPatriarchModel HMAddPatriarchModelWithDict:dict];
                [self.dataSource addObject:model];
            }
            
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        
        }
        
        else {
            [SVProgressHUD showErrorWithStatus:Obj[@"msg"]];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        }
    } Fail:^(NSError *Error) {
        [SVProgressHUD showErrorWithStatus:NetErr];
        
    }];
   
    
    
    
}

-(void) setEnterNetWork {
    
    NSMutableArray *idArray = [NSMutableArray new];
    //http://192.168.0.113:8080/StarShine/ys/yxhUser.do?action=saveThreeParent&uids=250,251
    for (NSIndexPath *indexPath in self.selectIndexs) {
        HMAddPatriarchModel *model =  self.dataSource[indexPath.row];
        [idArray addObject:model.uid];
    }
    
    NSString *uidStr = [idArray componentsJoinedByString:@","];
    NSString *url = [NSString stringWithFormat:@"yxhUser.do?action=saveThreeParent&uids=%@&lessonId=%@",uidStr,self.lessionId];
    
    NSLog(@"%@ %@",LLBaseURL(url),[AccountTool shareAccountTool].currentAccount.authCode);
    [SVProgressHUD setDefaultStyle:(SVProgressHUDStyleCustom)];
    [SVProgressHUD  setBackgroundColor:ColorRGB(4, 4, 4)];
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    [SVProgressHUD showWithStatus:LLLoading];

    [NetManager Get:LLBaseURL(url) Auth:YES Params:nil Success:^(id Obj) {
//        [SVProgressHUD dismiss];
        if ([[Obj valueForKey:@"code"]integerValue] == 1000) {
            [SVProgressHUD showSuccessWithStatus:@"新增家长成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (self.addSuccessBlock) {
                    self.addSuccessBlock();
                }
                [self.navigationController popViewControllerAnimated:YES];
            });
            
            
        

        } else {
            [SVProgressHUD showErrorWithStatus:Obj[@"msg"]];
        }
    } Fail:^(NSError *Error) {
        [SVProgressHUD showErrorWithStatus:NetErr];

    }];
    
    
}



-(NSMutableArray *)dataSource {
    if (_dataSource == nil) {
        _dataSource = [NSMutableArray new];
    }
    return _dataSource;
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.searchTextField resignFirstResponder];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:ColorRGB(255,255,255)}]; //设置标题颜色
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(47, 204, 138)] forBarMetrics:(UIBarMetricsDefault)];//设置导航栏颜色

    [SVProgressHUD dismiss];
}


- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(255, 255, 255)] forBarMetrics:(UIBarMetricsDefault)];//设置导航栏颜色
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:ColorRGB(51,51,51)}];//设置标题颜色
}


-(NSMutableArray *)selectIndexs {
    if (!_selectIndexs) {
        _selectIndexs = [NSMutableArray new];
    }
    return _selectIndexs;
}


@end
